#include "client.h"

class Client::Private
{
public:
    QUdpSocket* udpSocket{nullptr};
};

Client::Client(QObject *parent)
    : QObject{parent}, d(new Private)
{
    init();
}

Client::~Client()
{
    delete d->udpSocket;
}

void Client::init()
{
    d->udpSocket = new QUdpSocket;

    d->udpSocket->bind(QHostAddress::LocalHost, 7755);
    connect(d->udpSocket, &QUdpSocket::readyRead, this, &Client::readData);
}

void Client::readData()
{
    QByteArray data;
    while (d->udpSocket->hasPendingDatagrams()) {
        data.resize(d->udpSocket->pendingDatagramSize());
        d->udpSocket->readDatagram(data.data(), data.size());
    }
}

void Client::sendData(const QString &ip, int port, const QString &data)
{
    d->udpSocket->writeDatagram(data, QHostAddress(ip), port);
}
